// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // this.globalData.audioCtx = wx.createInnerAudioContext()
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res);
      }
    })
  },
  // Promise封装获取音乐信息请求
  getMusic(keywords) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://whale-cloud.vercel.app/search',
        data: {
          keywords: keywords
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data && res.data.code === 200) {
            resolve(res.data)
          }
        },
        fail(error) {
          reject(error)
        }
      })
    })
  },
  // Promise封装获取音乐src请求,在本地启动服务器时使用
  getMusicSrc(id) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://whale-cloud.vercel.app/song/url',
        data: {
          id: id
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data && res.data.code === 200) {
            resolve(res.data)
          } else {
            console.log(res.data);
          }
        },
        fail(error) {
          reject(error)
        }
      })
    })
  },
  // 使用网络服务器请求url
  getMusicSrcHttps(id) {
    return new Promise((resolve, reject) => {
      let url = "https://music.163.com/song/media/outer/url?id=" + id + ".mp3";
      if (url) {
        resolve(url)
      } else {
        reject(false)
      }
    })

  },
  // 搜索歌曲发起获取音乐信息请求,并设置歌曲信息
  async setMusic(keywords) {
    let data = await this.getMusic(keywords).then((value) => {
      console.log("setMusic", value.result);
      return value.result;
    })
    this.globalData.music.id = data.songs[0].id;
    this.globalData.music.poster = data.songs[0].artists[0].img1v1Url
    this.globalData.music.name = data.songs[0].name,
    this.globalData.music.author = data.songs[0].artists[0].name;
  },
  // 发起获取音乐src请求
  async setMusicSrc(id) {
    /**
     * 在本地启用服务器获取url时使用getMusic()接口
     * 从网络获取url时使用getMusicHttps()接口
     */
    let data = await this.getMusicSrcHttps(id).then((res) => {
      console.log("setMusicSrc", res);
      return res;
    })
    this.globalData.music.src = data
    return new Promise((resolve,reject)=>{
      if(data){
        resolve(true)
      }else{
        reject(false)
      }
    })
  },
  // 搜索歌曲
  async seachMusic(keywords) {
    let data = await this.getMusic(keywords).then((value) => {
      console.log("seachMusic", value.result);
      return value.result;
    })
    this.globalData.songs = data.songs;
  },  
  // 初始化测试
   setData() {
    this.setMusicSrc(this.globalData.musicList[this.globalData.musicListIndex])
    this.setMusic(this.globalData.musicList[this.globalData.musicListIndex])
    this.seachMusic('有何不可')
  },
  // 播放当前歌曲
  playAudio() {
    this.globalData.playControls = 'pause';
    this.globalData.audioCtx.play();
  },
  // 暂停播放
  pauseAudio() {
    this.globalData.playControls = 'stop'
    this.globalData.audioCtx.pause();
  },
  // 播放下一首 
  nextAudio() {
    this.globalData.musicListIndex++;
    if (this.globalData.musicListIndex > this.globalData.musicList.length - 1) {
      this.globalData.musicListIndex = this.globalData.musicList.length - 1;
      this.nowAudio();
      
    } else {
      this.nowAudio();
    }

  },
  // 播放当前歌曲
  async nowAudio() {
   await this.setMusic(this.globalData.musicList[this.globalData.musicListIndex]).then(async ()=>{
     await this.setMusicSrc(this.globalData.musicList[this.globalData.musicListIndex])
   }).then(async ()=>{
    this.globalData.playControls = 'stop'
    this.playControls()
    this.globalData.playControls = 'pause'
   }) 
   

  },
  // 播放上一首 
  prevAudio() {
    this.globalData.musicListIndex--;
    if (this.globalData.musicListIndex < 0) {
      this.globalData.musicListIndex = 0;
      this.nowAudio();
    } else {
      this.nowAudio();
    }
  },
  playControls() {
    if (this.globalData.playControls == 'stop') {
      console.log("play");
      this.playAudio()
      // this.changIconPause();
    } else if (this.globalData.playControls == 'pause') {
      console.log("pause");
      this.pauseAudio();
      // this.changeIconStop();
    }
  },
  globalData: {
    userInfo: null,
    // 播放列表
    musicList: [491950409, 167876, 27612225, 28987654, 412902950],
    musicListIndex: 0,
    audioCtx: null,
    music: {
      id: Number,
      poster: '',
      name: '',
      author: '',
      src: ''
    },
    songs: [],
    playControls: 'stop',
  }
})